package com.zqw.filter;

import com.zqw.pojo.AdminPojo;
import com.zqw.util.StaticUrl;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("utf-8");
        StringBuffer requestURL = request.getRequestURL();
        String servletPath = request.getServletPath();
        if(servletPath.equals("/")){
            response.sendRedirect("jump");
            return;
        }
        if(servletPath.indexOf(".")>0){
            if(StaticUrl.STATIC_RES.contains(servletPath.substring(servletPath.lastIndexOf(".")))){
                filterChain.doFilter(request,response);
                return;
            }
        }
        if(StaticUrl.STATIC_URL.contains(servletPath)){
            filterChain.doFilter(request,response);
            return;
        }
        AdminPojo admin = (AdminPojo)request.getSession().getAttribute("admin");
        if(admin==null){
            response.sendRedirect("jump");
            return;
        }
        String auths = (String)request.getSession().getAttribute("auths");
        response.setContentType("text/html;charset=utf-8");
        if(!auths.contains(servletPath)){
            response.getWriter().write("<h1>权限不够，充值</h1>");
            return;
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
